package cn.pjz.service.impl;

import cn.pjz.basic.result.JSONResult;
import cn.pjz.domain.Token;
import cn.pjz.domain.User;
import cn.pjz.mapper.TokenMapper;
import cn.pjz.mapper.UserMapper;
import cn.pjz.service.ITokenService;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;


/**
 * @author 阿洲
 */
@Service
public class ITokenServiceImpl  extends ServiceImpl<TokenMapper, Token> implements ITokenService {

    @Autowired
    private TokenMapper mapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Token save() {
        //生产token
        String randomString = RandomStringUtils.randomAlphabetic(20);
        //生产验证码
        String vCode = RandomStringUtils.randomAlphabetic(6);
        //创建token对象
        Token token = new Token();

        token.setToken(randomString);
        //生成随机ID
        Random r = new Random();

        Long l = r.nextLong();

        token.setId(l);

        //存入
        mapper.insert(token);

        mapper.selectById(l);


        return token;
    }

    @Override
    public JSONResult login(User user, Token token) {

        //查询Token
        Token t1 = mapper.selectById(token.getId());

        if(!t1.getToken().equals(token.getToken())){
            return JSONResult.error("没有获取到令牌或者令牌已过期");
        }else if(!t1.getVerificationCode().equals(token.getVerificationCode())){
            return JSONResult.error("验证码错误");
        }
        //校验密码
        User u1 = userMapper.selectById(user.getId());

        if(!u1.getPassword().equals(user.getPassword())){
            return JSONResult.error("账号或密码错误");
        }
        return JSONResult.success();
    }
}
